package com.peaker.advertisingpro.utils


import java.text.DateFormat
import java.text.DecimalFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*


/**
 *  @ 作者 CODE_LYF
 *  @ 时间   2021/4/18.
 *  代码人生
 */
object DateTimeUtil {
    // 获取当前时间n[]之后的时间的日期时间字符串（N的单位为Calendar的那些表示时间的常量）
    fun getNLaterDateTimeString(nType: Int, n: Int): String? {
        val date = Date()
        val c: Calendar = GregorianCalendar()
        c.setTime(date)
        c.add(nType, n)
        return CalendarToString(c)
    }

    // millis to datetime
    fun getDateTimeStringFromMillis(millis: Long): String? {
        val date = Date(millis)
        return DateToString(date)
    }

    // 把日期时间字符串的时间转换成毫秒值（RTC）
    fun stringToMillis(dateTime: String?): Long {
        val c: Calendar = StringToGregorianCalendar(dateTime)
        return c.timeInMillis
    }

    // 获取两个日期时间字符串表示的时间之间的毫秒差值
    fun getDifMillis(dateTime1: String?, dateTime2: String?): Long {
        return stringToMillis(dateTime1) - stringToMillis(dateTime2)
    }

    // 输入一个表示日期或时间的整型数，输出"01"或"23"这样格式的字符串
    fun getDoubleNumString(n: Int): String? {
        val num = n % 60
        return if (num < 10) {
            "0$num"
        } else {
            num.toString() + ""
        }
    }

    // 获取标准日期时间字符串的整型的日期值，如："2015-01-21 00:00:00"，返回：21
    fun getDayOfMonth(dateTime: String?): Int {
        val c: Calendar = StringToGregorianCalendar(dateTime)
        return c.get(Calendar.DAY_OF_MONTH)
    }

    // 获取当前时间的日期时间字符串，格式："yyyy-MM-dd HH:mm:ss"
    fun getCurrentDateTimeString(): String? {
        val date = Date()
        return DateToString(date)
    }

    // 获取当前的"yyyy-MM-dd"日期格式字符串
    fun getCurrentDateString(): String? {
        val date = Date()
        return DateToString(date)!!.substring(0, 10)
    }

    // 获取当前的"yyyy-MM"日期格式字符串
    fun getCurrentMonthString(): String? {
        val date = Date()
        return DateToString(date)!!.substring(0, 7)
    }

    // 获取当前的"HH:mm"时间格式字符串
    fun getCurrentTimeString(): String? {
        val date = Date()
        return DateToString(date)!!.substring(11, 16)
    }

    // 获取当前的"HH:mm:ss"时间格式字符串
    fun getCurrentTimeLongString(): String? {
        val date = Date()
        return DateToString(date)!!.substring(11, 19)
    }

    // 由日期时间字符串生成“11月1日 星期一”这样格式的字符串
    fun getShortDateTimeOfWeek(dateTime: String?): String? {
        val c: Calendar = StringToGregorianCalendar(dateTime)
        val month: Int = c.get(Calendar.MONTH) + 1
        val day: Int = c.get(Calendar.DAY_OF_MONTH)
        val weekStr = arrayOf(
            "星期日", "星期一", "星期二", "星期三", "星期四",
            "星期五", "星期六"
        )
        val week = weekStr[c.get(Calendar.DAY_OF_WEEK) - 1]
        return month.toString() + "月" + day + "日" + "  " + week
    }

    // 由日期时间字符串生成“2015年11月1日 星期一”这样格式的字符串
    fun getDateTimeOfWeek(dateTime: String?): String? {
        val c: Calendar = StringToGregorianCalendar(dateTime)
        val year: Int = c.get(Calendar.YEAR)
        val month: Int = c.get(Calendar.MONTH) + 1
        val day: Int = c.get(Calendar.DAY_OF_MONTH)
        val weekStr = arrayOf(
            "星期日", "星期一", "星期二", "星期三", "星期四",
            "星期五", "星期六"
        )
        val week = weekStr[c.get(Calendar.DAY_OF_WEEK) - 1]
        return year.toString() + "年" + month + "月" + day + "日" + "  " + week
    }

    // 由日期时间字符串生成“2015年11月1日 05:43”这样格式的字符串
    fun getDateTimeOfHourMinute(dateTime: String): String? {
        var result = ""
        val date = dateTime.split(" ").toTypedArray()[0]
        val time = dateTime.split(" ").toTypedArray()[1]
        val dateArr = date.split("-").toTypedArray()
        val timeArr = time.split(":").toTypedArray()
        val year = dateArr[0].toInt()
        val month = dateArr[1].toInt()
        val day = dateArr[2].toInt()
        result = (year.toString() + "年" + month + "月" + day + "日" + "  " + timeArr[0] + ":"
                + timeArr[1])
        return result
    }

    // 用年月日生成日期字符串，month取值范围：[0,13]
    fun getDateString(year: Int, month: Int, day: Int): String? {
        val m: String
        val d: String
        m = if (month >= 9) {
            (month + 1).toString() + ""
        } else {
            "0" + (month + 1)
        }
        d = if (day >= 10) {
            day.toString() + ""
        } else {
            "0$day"
        }
        return "$year-$m-$d"
    }

    // 用年月生成年月日期字符串，month取值范围：[0,13]
    fun getDateString(year: Int, month: Int): String? {
        val m: String
        var d: String
        m = if (month >= 9) {
            (month + 1).toString() + ""
        } else {
            "0" + (month + 1)
        }
        return "$year-$m"
    }

    // 用时、分生成时间字符串
    fun getTimeString(hour: Int, minute: Int): String? {
        val h: String
        val m: String
        h = if (hour >= 10) {
            hour.toString() + ""
        } else {
            "0$hour"
        }
        m = if (minute >= 10) {
            minute.toString() + ""
        } else {
            "0$minute"
        }
        return "$h:$m"
    }

    // 用时、分、秒生成时间字符串
    fun getTimeString(hour: Int, minute: Int, second: Int): String? {
        val h: String
        val m: String
        val c: String
        h = if (hour >= 10) {
            hour.toString() + ""
        } else {
            "0$hour"
        }
        m = if (minute >= 10) {
            minute.toString() + ""
        } else {
            "0$minute"
        }
        c = if (second >= 10) {
            second.toString() + ""
        } else {
            "0$second"
        }
        return "$h:$m:$c"
    }

    // 该内部类是用于对日期时间字符串数组进行排序的
    class DateTimeString(private val mDateTimeStr: String) : Comparable<DateTimeString?> {



        override fun toString(): String {
            return mDateTimeStr
        }

        override fun compareTo(other: DateTimeString?): Int {
            return compareDateTimeString(
                mDateTimeStr,
                other.toString()
            )
        }

    }

    // 对日期时间字符串数组进行排序,返回排序后的数组（排序后的顺序是从小到大）
    fun sortDateTimeStringArray(dateTimeStringArray: Array<String?>): Array<String?>? { // 将日期时间字符串数组转换成DateTimeString类型数组，DateTimeString实现了Comparable接口，可以进行排序
        val tmpArray = arrayOfNulls<DateTimeString>(dateTimeStringArray.size)
        // 生成tmpArray数组
        var i = 0

        for (str in dateTimeStringArray) {
            tmpArray[i++] = DateTimeString(str!!)
        }
        // 对tmpArray进行排序
        Arrays.sort(tmpArray)
        val result = arrayOfNulls<String>(tmpArray.size)
        i = 0
        for (str in tmpArray) {
            result[i++] = str.toString()
        }
        return result
    }

    // 比较两个日期时间字符串的大小，如果str1比str2早，则返回-1，如果相等返回0，否则返回1
    fun compareDateTimeString(str1: String?, str2: String?): Int {
        val d1: Date = StringToDate(str1)
        val d2: Date = StringToDate(str2)
        return if (d1.getTime() - d2.getTime() < 0) {
            -1
        } else if (d1.getTime() - d2.getTime() > 0) {
            1
        } else {
            0
        }
    }

    // 时间日期字符串转换成Date对象
// 注：dateTimeStr带不带前导0都是可以的，比如"2011-01-01 01:02:03"和"2011-1-1 1:2:3"都是合法的
    fun StringToDate(dateTimeStr: String?): Date {
        var date = Date()
        // DateFormat fmt = DateFormat.getDateTimeInstance();
        val fmt: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        try {
            date = fmt.parse(dateTimeStr)
            return date
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return date
    }

    // Date对象转换成日期时间字符串
    fun DateToString(date: Date?): String? {
        var dateTimeStr: String? = null
        // DateFormat fmt = DateFormat.getDateTimeInstance();
        val fmt: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        dateTimeStr = fmt.format(date)
        return dateTimeStr
    }

    // 字符串转换成Calendar
    fun StringToGregorianCalendar(dateTimeStr: String?): Calendar {
        val date: Date = StringToDate(dateTimeStr)
        val calendar: Calendar = GregorianCalendar()
        calendar.setTime(date)
        return calendar
    }

    // Calendar转换成String
    fun CalendarToString(calendar: Calendar): String? {
        val date: Date = (calendar as GregorianCalendar).getTime()
        return DateToString(date)
    }

    // 获取日期时间格式字符串表示的两日期时间之间相隔的天数（天数可为浮点型） AC
    fun getDayNumDif(
        str1: String?,
        str2: String?
    ): Double { // DateFormat fmt = DateFormat.getDateTimeInstance();
        val fmt: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        try {
            val d1: Date = fmt.parse(str1)
            val d2: Date = fmt.parse(str2)
            val dif: Long = Math.abs(d1.getTime() - d2.getTime())
            val dayDif = dif.toDouble() / 1000 / (24 * 60 * 60)
            // 保留两位小数
            val df = DecimalFormat("0.00")
            return df.format(dayDif).toDouble()
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return (-1).toDouble()
    }

    // 求算术平均值函数，保留2位小数
    fun getAverage(data: DoubleArray): Double {
        var sum = 0.0
        for (i in data.indices) {
            sum += data[i]
        }
        val df = DecimalFormat("0.00")
        return df.format(sum / data.size).toDouble()
    }

    // 输入一个时间日期字符串（格式：“yyyy-MM-dd HH:mm:ss”），输出num天后的时间日期字符串（num可为浮点数）
    fun getNDayLatterDateTime(str: String?, num: Double): String? { // 创建日期时间格式对象fmt
// DateFormat fmt = DateFormat.getDateTimeInstance();
        val fmt: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        try {
            val curDate: Date = fmt.parse(str)
            val calendar = GregorianCalendar()
            calendar.setTime(curDate)
            calendar.add(Calendar.SECOND, (num * (24 * 60 * 60)).toInt())
            val newDate: Date = calendar.getTime()
            return fmt.format(newDate)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return ""
    }
}